package downloader

import (
	"fmt"
	"path/filepath"

	"github.com/anacrolix/torrent"
)

type TorrentDownloader struct {
	BaseDownloader
	client *torrent.Client
}

func NewTorrentDownloader(config *Config) *TorrentDownloader {
	return &TorrentDownloader{
		BaseDownloader: BaseDownloader{
			config:   config,
			stopChan: make(chan struct{}),
		},
	}
}

func (d *TorrentDownloader) Download(urlStr string) error {
	cfg := torrent.NewDefaultClientConfig()
	cfg.DataDir = d.config.OutputDir

	var err error
	d.client, err = torrent.NewClient(cfg)
	if err != nil {
		return fmt.Errorf("failed to create torrent client: %w", err)
	}
	defer d.client.Close()

	t, err := d.client.AddMagnet(urlStr)
	if err != nil {
		return fmt.Errorf("failed to add magnet/torrent: %w", err)
	}

	<-t.GotInfo()
	t.DownloadAll()

	d.initProgress(t.Info().TotalLength(), filepath.Base(t.Name()))

	// Wait for download
	for {
		select {
		case <-d.stopChan:
			return nil
		default:
			if t.BytesCompleted() == t.Info().TotalLength() {
				return nil
			}
			d.updateProgress(t.BytesCompleted())
		}
	}
}

func (d *TorrentDownloader) Stop() error {
	if d.client != nil {
		d.client.Close()
	}
	close(d.stopChan)
	return nil
}

func (d *TorrentDownloader) Progress() float64 {
	d.mu.Lock()
	defer d.mu.Unlock()
	if d.totalSize == 0 {
		return 0
	}
	return float64(d.downloaded) / float64(d.totalSize) * 100
}

func (d *TorrentDownloader) Speed() int64 {
	return 0 // TODO: Implement speed calculation
}
